﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using EnterpriseFund.Common;
using System.Data;
using DevExpress.Web.Mvc;

namespace EnterpriseFund.Controllers
{
        [OutputCache(Duration = 0, VaryByParam = "none")]
    public class AllowanceFileManageController : AdminBaseController
    {
        //
        // GET: /AllowanceFileManage/
            [AuthorityActionFilter("m_AllowanceFileManage", Order = 1)]
            [LogPageActionFilter("资金汇总表管理", Order = 2)]
        public ActionResult Index()
        {
            string strwhere = " FFileNo is null";
            List<Model.AllowanceFile> AllowanceFileList = new List<Model.AllowanceFile>();
            AllowanceFileList = GetAllowanceFileListList(strwhere, 1);
            return View(AllowanceFileList);
        }

        #region  grid绑定

        public ActionResult AllowanceFilePartial()
        {
            int pageIndex = Request.Params["pageIndex"] == null ? 0 : int.Parse(Request.Params["pageIndex"].ToString());
            int pageCount = Request.Params["PageCount"] == null ? 0 : int.Parse(Request.Params["PageCount"].ToString());
            int pageRowSize = Request.Params["pageRowSize"] == null ? 0 : int.Parse(Request.Params["pageRowSize"].ToString());
            int pageRowCount = Request.Params["pageRowCount"] == null ? 0 : int.Parse(Request.Params["pageRowCount"].ToString());
            string callbackArg = DevExpressHelper.CallbackArgument;

            string command = Request.Params["command"] == null ? "" : Request.Params["command"].ToString();

            if (command == "PAGERONCLICK")
            {
                string[] args = callbackArg.Split(new char[1] { '|' });
                string arg = args[args.Count() - 1];

                switch (arg)
                {
                    case "PBN;":
                        {
                            //下一页
                            pageIndex = pageIndex + 2;
                            break;
                        }
                    case "PBP;":
                        {
                            //上一页
                            //pageIndex = pageIndex;
                            break;
                        }
                    case "PBL;":
                        {
                            //最后一页
                            pageIndex = pageCount;
                            break;
                        }
                    case "PBF;":
                        {
                            //第一页
                            pageIndex = 1;
                            break;
                        }
                    default:
                        {
                            //点击数字页码
                            string tempIndex = arg.Replace("PN", "");
                            tempIndex = tempIndex.Replace(";", "");
                            if (RegExp.IsNumeric(tempIndex))
                            {
                                pageIndex = int.Parse(tempIndex) + 1;
                            }
                            break;
                        }

                }
            }
            else
            {
                pageIndex = pageIndex + 1;
            }
            string strwhere = "1=1 ";
            string FStatus = Request.Params["FStatus"];
            string NSRBM = Request.Params["NSRBMQ"];
            if (!string.IsNullOrEmpty(FStatus))
            {
              switch(FStatus)
              {
                  case "0":
                 strwhere += "  and FStatus='" + FStatus + "'";
                      break;
                  case "1":

              strwhere += "  and (FStatus='1' or FStatus='2')";
                    break;
               } 
            }
            else
            {
                strwhere += "  and FFileNo is null";
            }

            if (!string.IsNullOrEmpty(NSRBM))
            {
                strwhere += " and  (FFileName like '%" + NSRBM + "%' or FFileNo like '%" + NSRBM + "%' )";
            }
           
            List<Model.AllowanceFile> AllowanceFileList = new List<Model.AllowanceFile>();
            AllowanceFileList = GetAllowanceFileListList(strwhere, pageIndex);
            return PartialView("AllowanceFilePartial", AllowanceFileList);
        }

        /// <summary>
        /// 获取定义的工作时间数据
        /// </summary>
        /// <param name="strWhere">查询条件</param>
        /// <param name="pageIndex">第几页</param>
        /// <returns>查询出来的数据</returns>
        private List<Model.AllowanceFile> GetAllowanceFileListList(string strWhere, int pageIndex)
        {
            BLL.Common commonBll = new BLL.Common();
            BLL.AllowanceFile AllowanceFileBLL = new BLL.AllowanceFile();
            string fiedls = "FAllowanceFileID";
            int total;
            DataSet ds = commonBll.GetListByPage("fund.v_AllowanceFile", fiedls, Common.GlobalConstant.CONSTRING_PAGESIZE, pageIndex, strWhere, "FStatus", out total);
            List<Model.AllowanceFile> AllowanceFileList = AllowanceFileBLL.DataTableToList(ds.Tables[0]);
            foreach (Model.AllowanceFile a in AllowanceFileList)
            {
                a.sumFAmount = a.sumFAmount / 10000;
            }
            List<Model.AllowanceFile> AllowanceFileAllList = new List<Model.AllowanceFile>();
            total = AllowanceFileBLL.GetRecordCount(strWhere);
            int pageRowSize = Common.GlobalConstant.CONSTRING_PAGESIZE;
            for (int i = 0; i < total; i++)
            {
                AllowanceFileAllList.Add(null);
            }
            for (int i = 0; i < pageRowSize; i++)
            {
                if (AllowanceFileList.Count > i)
                {
                    AllowanceFileAllList[((pageIndex - 1) * pageRowSize) + i] = AllowanceFileList[i];
                }
            }

            return AllowanceFileAllList;
        }

        public ActionResult SelectIssuePartial()
        {
            int pageIndex = Request.Params["pageIndex"] == null ? 0 : int.Parse(Request.Params["pageIndex"].ToString());
            int pageCount = Request.Params["PageCount"] == null ? 0 : int.Parse(Request.Params["PageCount"].ToString());
            int pageRowSize = Request.Params["pageRowSize"] == null ? 0 : int.Parse(Request.Params["pageRowSize"].ToString());
            int pageRowCount = Request.Params["pageRowCount"] == null ? 0 : int.Parse(Request.Params["pageRowCount"].ToString());
            string callbackArg = DevExpressHelper.CallbackArgument;

            string command = Request.Params["command"] == null ? "" : Request.Params["command"].ToString();

            if (command == "PAGERONCLICK")
            {
                string[] args = callbackArg.Split(new char[1] { '|' });
                string arg = args[args.Count() - 1];

                switch (arg)
                {
                    case "PBN;":
                        {
                            //下一页
                            pageIndex = pageIndex + 2;
                            break;
                        }
                    case "PBP;":
                        {
                            //上一页
                            //pageIndex = pageIndex;
                            break;
                        }
                    case "PBL;":
                        {
                            //最后一页
                            pageIndex = pageCount;
                            break;
                        }
                    case "PBF;":
                        {
                            //第一页
                            pageIndex = 1;
                            break;
                        }
                    default:
                        {
                            //点击数字页码
                            string tempIndex = arg.Replace("PN", "");
                            tempIndex = tempIndex.Replace(";", "");
                            if (RegExp.IsNumeric(tempIndex))
                            {
                                pageIndex = int.Parse(tempIndex) + 1;
                            }
                            break;
                        }

                }
            }
            else
            {
                pageIndex = pageIndex + 1; 
            }
            string strwhere = " 1=1  ";
            string FNewFinancePropNo = Request.Params["FFinancePropNo"];
            strwhere += " and  FNewFinancePropNo='" + FNewFinancePropNo + "'";
            List<Model.VAllowanceIssueCheckSelectIssue> vallowanceIssueCheckSelectIssueList = new List<Model.VAllowanceIssueCheckSelectIssue>();
            vallowanceIssueCheckSelectIssueList = GetSelectIssueListList(strwhere, pageIndex);
            return PartialView("SelectIssuePartial", vallowanceIssueCheckSelectIssueList);
        }

        /// <summary>
        /// 获取定义的工作时间数据
        /// </summary>
        /// <param name="strWhere">查询条件</param>
        /// <param name="pageIndex">第几页</param>
        /// <returns>查询出来的数据</returns>
        private List<Model.VAllowanceIssueCheckSelectIssue> GetSelectIssueListList(string strWhere, int pageIndex)
        {
            BLL.Common commonBll = new BLL.Common();
            BLL.VAllowanceIssueCheckSelectIssue AllowanceFileBLL = new BLL.VAllowanceIssueCheckSelectIssue();
            string fiedls = "KeyNo";
            int total;
            DataSet ds = commonBll.GetListByPage("fund.v_AllowanceIssueCheckSelectIssue", fiedls, Common.GlobalConstant.CONSTRING_PAGESIZE, pageIndex, strWhere, "FIssueID", out total);
            List<Model.VAllowanceIssueCheckSelectIssue> vallowanceIssueCheckSelectIssueList = AllowanceFileBLL.DataTableToList(ds.Tables[0]);
            List<Model.VAllowanceIssueCheckSelectIssue> vallowanceIssueCheckSelectIssueAllList = new List<Model.VAllowanceIssueCheckSelectIssue>();
            total = AllowanceFileBLL.GetRecordCount(strWhere);
            int pageRowSize = Common.GlobalConstant.CONSTRING_PAGESIZE;
            for (int i = 0; i < total; i++)
            {
                vallowanceIssueCheckSelectIssueAllList.Add(null);
            }
            for (int i = 0; i < pageRowSize; i++)
            {
                if (vallowanceIssueCheckSelectIssueList.Count > i)
                {
                    vallowanceIssueCheckSelectIssueAllList[((pageIndex - 1) * pageRowSize) + i] = vallowanceIssueCheckSelectIssueList[i];
                }
            }

            return vallowanceIssueCheckSelectIssueAllList;
        }
        
        #endregion  grid绑定

        public DataTable GetShowData2(DataTable dt)
        {
            dt.Columns.Add("cz");
            dt.Columns.Add("je",typeof(decimal));
            foreach (DataRow drz in dt.Rows)
            {
                drz["cz"] = "mx";
                drz["je"] = decimal.Parse(drz["FAmount"].ToString()) / 10000;
            }
            
            decimal sumse = dt.AsEnumerable().Sum(p => p.Field<decimal>("je"));
            DataRow dr = dt.NewRow();
            dr["cz"] = "合计";
            dr["je"] = sumse;
            dt.Rows.Add(dr);
            return dt;

        }

        public DataTable GetShowData(DataTable dt)
        {
            dt.Columns.Add("cz");
            foreach (DataRow drz in dt.Rows)
            {
                drz["cz"] = "mx";
                drz["je"] = decimal.Parse(drz["je"].ToString()) / 10000;
            }
            dt.Columns["je"].DataType = typeof(decimal);
            decimal sumse = dt.AsEnumerable().Sum(p => p.Field<decimal>("je"));
            DataRow dr = dt.NewRow();
            dr["cz"] = "合计";
            dr["je"] = sumse;
            dt.Rows.Add(dr);
            return dt;

        }

        public ActionResult AllowanceFileEdit(string financePropNo, string issueIDList, string FAllowanceFileID="")
        {
            if (FAllowanceFileID != null && FAllowanceFileID != "")
            {
                BLL.FinanceProp financePropBLL = new BLL.FinanceProp();
                BLL.AllowanceFile allowanceFileBLL = new BLL.AllowanceFile();
                Model.AllowanceFile model = allowanceFileBLL.GetModel(FAllowanceFileID);
                ViewData["FFileName"] = model.FFileName;
                BLL.AllowanceFileEntry allowanceFileEntryBLL = new BLL.AllowanceFileEntry();
                DataTable dt = allowanceFileEntryBLL.GetList("FAllowanceFileID='" + model.FAllowanceFileID + "'").Tables[0];
                Model.FinanceProp fmodel = financePropBLL.GetModel(model.FFinancePropNo);
                ViewData["FYear"] = OperateSession.get(GlobalConstant.PARAM_SYSYEAR);
                ViewData["FIssueNo"] = fmodel.FFinancePropName;
                ViewData["FPeriod"] = model.FPeriod;
                ViewData["showdata"] = GetShowData2(dt);
                ViewData["FFinancePropNo"] = model.FFinancePropNo;
                ViewData["FAllowanceFileID"] = model.FAllowanceFileID;
                
                DataSet ds = allowanceFileBLL.GetFIssueIDByFAllowanceFileID(FAllowanceFileID);
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    if (issueIDList!=null && issueIDList != "")
                    {
                        issueIDList += ",'" + dr["FIssueID"].ToString() + "'";
                    }
                    else
                    {
                        issueIDList += "'" + dr["FIssueID"].ToString() + "'";
                    }
                }
                ViewData["IssueIDList"] = issueIDList;
            }
            else
            {
                BLL.FinanceProp financePropBLL = new BLL.FinanceProp();
                BLL.AllowanceFile allowanceFileBLL = new BLL.AllowanceFile();
                Model.FinanceProp model = financePropBLL.GetModel(financePropNo);
                BLL.AllowanceIssueEntry allowanceIssueEntryBLL = new BLL.AllowanceIssueEntry();
                DataTable dt = allowanceIssueEntryBLL.GetAllowanceFileList(financePropNo, issueIDList).Tables[0];
                ViewData["FYear"] = OperateSession.get(GlobalConstant.PARAM_SYSYEAR);
                ViewData["FIssueNo"] = model.FFinancePropName;
                ViewData["FPeriod"] = allowanceFileBLL.GetMaxPeriod(OperateSession.get(GlobalConstant.PARAM_SYSYEAR), financePropNo);
                ViewData["showdata"] = GetShowData(dt);
                ViewData["FFinancePropNo"] = financePropNo;
                ViewData["IssueIDList"] = issueIDList;
            }
            return View("AllowanceFileEdit");
        }

        public ActionResult AllowanceFileSave()
        {
            try
            {
                string nsdzdanList = Fetch.Post("hidNSRDZDAH");

                List<Model.AllowanceFileEntry> allowanceFileEntryList = new List<Model.AllowanceFileEntry>();
                string[] noList = nsdzdanList.Split(',');
                foreach (string n in noList)
                {
                    Model.AllowanceFileEntry model = new Model.AllowanceFileEntry();
                    model.NSRDZDAH = decimal.Parse(n);
                    model.FAmount = decimal.Parse(Fetch.Post("hid" + n + "je")) * 10000;
                    model.FNote = Fetch.Post(n + "FNote");
                    allowanceFileEntryList.Add(model);
                }

                Model.AllowanceFile AllowanceFileModel = new Model.AllowanceFile();
                AllowanceFileModel.FEntityNo = GlobalConstant.ENTITYNO;
                AllowanceFileModel.FPeriod = int.Parse(Fetch.Post("FPeriod"));
                string a=Common.Rmb.ArabToChn(decimal.Parse(AllowanceFileModel.FPeriod.ToString()));
                AllowanceFileModel.FFileName = string.Format(Fetch.Post("hidtitle"), a);
                AllowanceFileModel.FFinancePropNo = Fetch.Post("hidFFinancePropNo");
                AllowanceFileModel.FInsDate = DateTime.Now;
                AllowanceFileModel.FInsDeptNo = OperateSession.get(GlobalConstant.PARAM_DEPTNO);
                AllowanceFileModel.FInsEmpNo = OperateSession.get(GlobalConstant.PARAM_FEMPLNO);
                AllowanceFileModel.FInsIP = GenerateUtil.GetClientIPv4Address();
                AllowanceFileModel.FYear = decimal.Parse(OperateSession.get(GlobalConstant.PARAM_SYSYEAR));
                AllowanceFileModel.FStatus = "1";
                BLL.AllowanceFile allowanceFileBLL = new BLL.AllowanceFile();
                string issueIDList = Fetch.Post("hidIssueIDList");
                string allowanceFileID = Fetch.Post("hidFAllowanceFileID"); 
                AllowanceFileModel.FAllowanceFileID = allowanceFileID;
                if (allowanceFileID != null && allowanceFileID != "")
                {
                    allowanceFileBLL.UpdateFile(allowanceFileEntryList, AllowanceFileModel, issueIDList);

                    WorkFlow("t_AllowanceFile", "10", allowanceFileID, "start", "");
                }
                else
                {
                    string id = allowanceFileBLL.Add(allowanceFileEntryList, AllowanceFileModel, issueIDList);

                    WorkFlow("t_AllowanceFile", "10", id, "start", "");
                }
                ViewData["jsAlert"] = "操作成功";
            }
            catch (Exception ex)
            {
                ViewData["jsAlert"] = ex.Message;
            }
            string allowanceFileID2 = Fetch.Post("hidFAllowanceFileID");
            return AllowanceFileEdit(Fetch.Post("hidFFinancePropNo"), Fetch.Post("hidIssueIDList"), allowanceFileID2);
        }

        public ActionResult SelectIssue()
        {
            BLL.FinanceProp financePropBLL = new BLL.FinanceProp();
            ViewData["FinancePropList"] = financePropBLL.GetModelList(" FFinancePropNo in ( SELECT DISTINCT FNewFinancePropNo FROM fund.v_AllowanceIssueCheckSelectIssue WHERE nsrcount>0)");
            return View();
        }

        public ActionResult Create()
        {
            string financePropNo = Fetch.Post("hidFFinancePropNo");
            string issueIDList = Fetch.Post("hidIssueIDList");

            string[] idArr = issueIDList.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
            string issueID = "";
            foreach (string id in idArr)
            {
                if (issueID != "")
                {
                    issueID += ",'" + id + "'";
                }
                else
                {
                    issueID += "'" + id + "'";
                }
            }
            return AllowanceFileEdit(financePropNo, issueID);
        }

        public ActionResult AllowanceFileLook(string FAllowanceFileID)
        {
            BLL.AllowanceFile allowanceFileBLL = new BLL.AllowanceFile();
            Model.AllowanceFile model =  allowanceFileBLL.GetModel(FAllowanceFileID);
            ViewData["FFileName"] = model.FFileName;
            ViewData["FAllowanceFileID"] = FAllowanceFileID;
            BLL.AllowanceFileEntry allowanceFileEntryBLL = new BLL.AllowanceFileEntry();
            DataTable dt = allowanceFileEntryBLL.GetList("FAllowanceFileID='" + model.FAllowanceFileID + "'").Tables[0];
            ViewData["showdata"] = GetLookData(dt);
            return View();
        }


        public DataTable GetLookData(DataTable dt)
        {
            foreach (DataRow drz in dt.Rows)
            {
                drz["FAmount"] = decimal.Parse(drz["FAmount"].ToString()) / 10000;
            }
            dt.Columns["FAmount"].DataType = typeof(decimal);
            decimal sumse = dt.AsEnumerable().Sum(p => p.Field<decimal>("FAmount"));
            DataRow dr = dt.NewRow();
            dr["NSRMC"] = "合计";
            dr["FAmount"] = sumse;
            dt.Rows.Add(dr);
            return dt;

        }

        public string DelAllowanceFile(string FAllowanceFileID)
        {
            string str = string.Empty;
            if (null != FAllowanceFileID)
            {
                FAllowanceFileID = Fetch.estimateString(FAllowanceFileID, CheckGetEnum.Safety);
                BLL.AllowanceFile codeNameBll = new BLL.AllowanceFile();
                try
                {
                    codeNameBll.Delete(FAllowanceFileID);
                    str = "ok";
                }
                catch (Exception)
                {
                    str = "error";
                }
            }
            return str;
        }
    }
}
